import entity.Message;
import enums.ResponseType;
import request.message.MessageSendRequest;
import response.Response;
import response.message.MessageSendResponse;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.time.LocalDateTime;

public class ChatHandler extends KeyAdapter implements ActionListener {
    private ChatView chatView;

    public ChatHandler(ChatView chatView) {
        this.chatView = chatView;
    }

    public void actionPerformed(ActionEvent e) {
        JButton jButton = (JButton) e.getSource();
        String text = jButton.getText();
        if ("发送".equals(text)) {
            send();
        }
    }

    public void send() {
        String hostUserName = chatView.getHostUserName();
        String guestUserName = chatView.getGuestUserName();
        String content = chatView.getTextField().getText();
        Message message = new Message(hostUserName, guestUserName, LocalDateTime.now(), content);
        MessageSendRequest messageSendRequest = new MessageSendRequest(message);
        Response response = ConnectionUtil.makeConnection(messageSendRequest);
        if (response.getType() == ResponseType.MessageSend) {
            MessageSendResponse messageSendResponse = (MessageSendResponse) response;
            chatView.updateList(message);
        }
    }

    public void keyPressed(KeyEvent e) {
        if (KeyEvent.VK_ENTER == e.getKeyCode()) {
            send();
        }
    }
}
